<template>
  <div class="team">
    <div style="width: 100%;margin-bottom: 10px">
      <el-button style="float: right" type="primary" @click="centerDialogVisible=true">新建群组</el-button>
      <el-button style="float: right;margin-right: 5px" @click="centerDialogVisibleTeam = true">添加群组</el-button>
      <div style="clear: both"></div>
    </div>

    <div style="width: 100%">
      <el-card class="box-card">
        <div class="user-item" v-for="(item,index) in data" :key="index">
          <el-badge :id="item.id" :value="item.count" class="item" :hidden="!item.check">
            <div class="user-item" @click="item.check=false;isTalking = true;initWebSocket(item.crossNumber);">
              <el-avatar style="height: 40px;width: 40px"
                         :src="path"></el-avatar>
              <div
                  style="margin-left: 5px;display: flex;flex-direction: column;justify-content: center;align-items: flex-start">
                <span>{{ item.crossName }}</span>
                <span>{{ item.crossNumber }}</span>
              </div>
            </div>
          </el-badge>
        </div>
      </el-card>

      <el-card class="myCard" style="display: flex;justify-content: center;align-items: center">
        <div style="height: 100%;width: 750px" v-if="isTalking">
          <div id="talk" class="talk"
               style="width: 100%;height: 500px;border: 1px dashed #b4b1b1;margin-bottom: 20px;padding: 20px;box-sizing: border-box;overflow: auto;">
            <div v-for="(item,index) in talkinfo" :key="index" style="height: auto;width: 100%;margin-top: 5px;">
              <div style="width: 100%">
                <div style="width: 100%;height: 40px">
                  <el-avatar :class="{'left': item.id!=userId, 'right': item.id==userId}" :src="item.src"></el-avatar>
                  <span style="line-height: 40px" :class="{'left': item.id!=userId, 'right': item.id==userId}">{{
                      item.name
                    }}</span>
                </div>
                <div v-html="item.msg" :class="{'leftse': item.id!=userId, 'rightse': item.id==userId}"
                     style="width:45%;border-radius:8px;height: auto;border: 1px solid #cbc7c7;padding:10px;"></div>
              </div>
              <div class="clear"></div>
            </div>
          </div>
          <el-input placeholder="请输入聊天内容" v-model="input3" class="input-with-select">
            <el-button slot="append" @click="websocketsend" icon="el-icon-position"></el-button>
          </el-input>
        </div>
        <el-empty v-else description="聊天界面"></el-empty>
      </el-card>
    </div>

    <el-dialog
        title="新建群聊"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>
      <el-form label-width="100px" class="demo-ruleForm">
        <el-form-item label="群组名称">
          <el-input v-model="crossName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
        title="加入群聊"
        :visible.sync="centerDialogVisibleTeam"
        width="30%"
        center>
      <el-form label-width="100px" class="demo-ruleForm">
        <el-form-item label="群聊号">
          <el-input v-model="crossNumber"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisibleTeam = false">取 消</el-button>
        <el-button type="primary" @click="join">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Team",
  data() {
    return {
      centerDialogVisible: false,
      centerDialogVisibleTeam: false,
      crossName: "",
      data: [],
      isTalking: false,
      path: require("../assets/1群组.png"),
      talkinfo: [],
      input3: "",
      userId: null,
      userMsg: {},
      crossNumber: ""
    }
  },
  mounted() {
    this.getCross()
    this.getUserHimself()
  },
  destroyed() {
    this.websock.close() //离开路由之后断开websocket连接
  },
  methods: {
    async initWebSocket(crossNumber) { //初始化weosocket
      if (this.websock != undefined) {
        this.websock.close() //使用前清理上一次连接
      }
      console.log("建立连接")
      const wsuri = this.$websocket + this.userId + "/" + crossNumber;
      this.url = wsuri
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    async websocketonmessage(e) { //数据接收
      if (e.data.split(":")[0] == this.userId) {
        return
      }
      let speakerMsg
      await this.getUserMsg(e.data.split(":")[0]).then(data => {
        speakerMsg = data
      })
      let src
      await this.getimg(speakerMsg.logo).then(data => {
        src = data
      })
      let innimsg = {
        msg: e.data.split(":")[1],
        id: e.data.split(":")[0],
        src: src,
        name: speakerMsg.userName
      }
      this.talkinfo.push(innimsg)

      this.$nextTick(() => {
        let msg = document.getElementById('talk') // 获取对象
        msg.scrollTop = msg.scrollHeight // 滚动高度
      })
    },
    getUserMsg(id) {
      return new Promise(resolve => {
        this.$http.get("/user/getUserBasicsInfo/" + id).then(data => {
          resolve(data.data)
        })
      })
    },
    async websocketsend() {//数据发送
      let message = this.input3
      let src

      await this.getimg(this.userMsg.logo).then(data => {
        src = data
      })
      let innimsg = {
        msg: message,
        id: this.userId,
        src: src,
        name: this.userMsg.userName
      }
      this.talkinfo.push(innimsg)
      this.websock.send(message);
      this.input3 = ""
      this.$nextTick(() => {
        let msg = document.getElementById('talk') // 获取对象
        msg.scrollTop = msg.scrollHeight // 滚动高度
      })
    },
    websocketonopen() { //连接建立之后执行send方法发送数据

    },
    websocketonerror() {//连接建立失败重连
      // this.initWebSocket();
    },
    websocketclose(e) {  //关闭
      console.log(e)
      console.log('断开连接');
    },
    async getUserHimself() {
      await this.$http.get("/login/getUserHimself").then(async data => {
        data = data.data
        console.log(data)
        this.userMsg = data
        this.userId = data.id
      })
    },
    async getCross() {
      await this.$http.get("/cross/getCross").then(async data => {
        console.log(data)
        data = data.data
        this.data = data
      })
    },
    join() {
      let param = {
        crossNumber: this.crossNumber
      }
      this.$http.post("/cross/join", param).then(data => {
        if (data.code == 200) {
          this.$message.success("加入成功")
          this.centerDialogVisibleTeam = false
          this.getCross()
        } else if (data.code == 501) {
          this.$message.error(data.message)
          this.centerDialogVisibleTeam = false
        }
      })
    },
    add() {
      let param = {
        crossName: this.crossName
      }
      this.$http.post("/cross/creat", param).then(data => {
        if (data.code == 200) {
          this.$message.success("申请成功")
          this.centerDialogVisible = false
          this.getCross()
        } else if (data.code == 501) {
          this.$message.error(data.message)
          this.centerDialogVisible = false
        }
      })
    },
    getimg(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/file/img/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
  }
}
</script>

<style scoped>
.team {
  width: 980px;
  float: right;
}

.box-card {
  width: 200px;
  min-height: 450px;
  display: flex;
  flex-direction: column;
  float: left;
}

.myCard {
  width: 760px;
  height: 600px;
  margin-left: 15px;
  float: left;
}

.user-item {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-bottom: 1px solid #eaeaea;
  cursor: pointer;
}

.clear {
  clear: both;
}

.left {
  float: left;
}

.right {
  float: right;
}

.clear {
  clear: both;
}

.leftse {
  float: left;
  margin-left: 100px;
  margin-top: 10px;
  word-break: break-all;
  text-align: left;
}

.rightse {
  float: right;
  margin-right: 100px;
  margin-top: 10px;
  word-break: break-all;
  text-align: left;
}


.el-table .cell {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  white-space: normal;
  word-break: break-all;
  line-height: 23px;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>